<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="危险源" prop="sourceId">
        <el-select v-model="queryParams.sourceId" placeholder="请选择危险源">
          <el-option
            v-for="dict in sourceIdOptions"
            :key="dict.id"
            :label="dict.hazardName"
            :value="dict.id"
          ></el-option>
        </el-select>
<!--        <el-input-->
<!--          v-model="queryParams.sourceId"-->
<!--          placeholder="请输入危险源"-->
<!--          clearable-->
<!--          size="small"-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
      </el-form-item>
      <el-form-item label="修订时间"  prop="revisionTime">
        <el-date-picker clearable size="small"
                        v-model="queryParams.revisionTime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="选择修订时间">
        </el-date-picker>
<!--        <el-date-picker-->
<!--          v-model="daterangeRevisionTime"-->
<!--          size="small"-->
<!--          style="width: 240px"-->
<!--          value-format="yyyy-MM-dd"-->
<!--          type="daterange"-->
<!--          range-separator="-"-->
<!--          start-placeholder="开始日期"-->
<!--          end-placeholder="结束日期"-->
<!--        ></el-date-picker>-->
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['risk:control:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['risk:control:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['risk:control:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
		  :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['risk:control:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="controlList" @selection-change="handleSelectionChange" :row-class-name="tableRowClassName">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" width="50" align="center" >
        <template slot-scope="scope">
          <span>{{(queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1}}</span>
        </template>
      </el-table-column>
      <!--      <el-table-column label="主键ID" align="center" prop="id" />-->
      <el-table-column label="危险源" align="center" prop="sourceName" />
      <el-table-column label="修订时间" align="center" prop="revisionTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.revisionTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="作业项目" align="center" prop="operatingItem" />
      <el-table-column label="风险因素" align="center" prop="riskFactor" />
      <el-table-column label="输入类型种类" align="center" prop="inputType" :formatter="inputTypeFormat" />
      <el-table-column label="可能造成的危害种类" align="center" prop="hazardsType" :formatter="hazardsTypeFormat" />
      <el-table-column label="控制措施" align="center" prop="protectiveMeasures" />
      <el-table-column label="事故发生的可能性(L)" align="center" prop="l" :formatter="lFormat" />
      <el-table-column label="人员暴露于危险环境中的频繁程度(E)" align="center" prop="e" :formatter="eFormat" />
      <el-table-column label="一旦发生事故可能造成的后果(C)" align="center" prop="c" :formatter="cFormat" />
<!--      <el-table-column label="D" align="center" prop="d" />-->
      <el-table-column label="等级" align="center" prop="grade" :formatter="gradeFormat" />
      <el-table-column label="位置" align="center" prop="position" />
      <el-table-column label="责任主体" align="center" prop="responsibleParty" />
      <el-table-column label="避免失控措施或失控后缓解（控制）措施" align="center" prop="measures" />
<!--      <el-table-column label="备注" align="center" prop="remark" />-->
<!--      <el-table-column label="备用" align="center" prop="remarkSpare" />-->
<!--      <el-table-column label="备用1" align="center" prop="remarkSpare1" />-->
<!--      <el-table-column label="备用2" align="center" prop="remarkSpare2" />-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['risk:control:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['risk:control:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改风险、危险源识别评分及控制对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="160px">
        <el-row :gutter="20">
          <el-col :span="12" :xs="24">
        <el-form-item label="危险源" prop="sourceId">
          <el-select v-model="form.sourceId" placeholder="请选择危险源" style="width: 100%">
            <el-option
              v-for="dict in sourceIdOptions"
              :key="dict.id"
              :label="dict.hazardName"
              :value="dict.id"
            ></el-option>
          </el-select>
<!--          <el-input v-model="form.sourceId" placeholder="请输入危险源ID" />-->
        </el-form-item>
          </el-col>
          <el-col :span="12" :xs="24">
        <el-form-item label="修订时间" prop="revisionTime">
          <el-date-picker clearable size="small"
            v-model="form.revisionTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择修订时间" style="width: 100%">
          </el-date-picker>
        </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="作业项目" prop="operatingItem">
          <el-input v-model="form.operatingItem" placeholder="请输入作业项目" />
        </el-form-item>
        <el-form-item label="风险因素" prop="riskFactor">
          <el-input v-model="form.riskFactor" placeholder="请输入风险因素" />
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12" :xs="24">
        <el-form-item label="输入类型种类" prop="inputType">
          <el-select v-model="form.inputType" placeholder="请选择输入类型种类" style="width: 100%">
            <el-option
              v-for="dict in inputTypeOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
          </el-col>
          <el-col :span="12" :xs="24">
        <el-form-item label="可能造成的危害种类" prop="hazardsTypes">
          <el-select v-model="form.hazardsTypes" multiple placeholder="请选择可能造成的危害种类" style="width: 100%">
            <el-option
              v-for="dict in hazardsTypeOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="控制措施" prop="protectiveMeasures">
          <el-input v-model="form.protectiveMeasures" type="textarea" placeholder="请输入控制措施" />
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12" :xs="24">
        <el-form-item label="事故的可能性(L)" prop="l">
          <el-select v-model="form.l" placeholder="请选择" @change="handleSelectChangeL" style="width: 100%">
            <el-option
              v-for="dict in lOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel + '('  +dict.dictValue+ ')'"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
          <div style="margin-top: 5px;">
            <el-link style="font-size: 10px ; color: red" target="_blank" @click="showHelp">查看帮助文档</el-link>
          </div>
        </el-form-item>
          </el-col>
          <el-col :span="12" :xs="24">
        <el-form-item label="暴露在危险的程度(E)" prop="e">
          <el-select v-model="form.e" placeholder="请选择" @change="handleSelectChangeE" style="width: 100%">
            <el-option
              v-for="dict in eOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel + '('  +dict.dictValue+ ')'"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12" :xs="24">
        <el-form-item label="发生事故的后果(C)" prop="c">
          <el-select v-model="form.c" placeholder="请选择" @change="handleSelectChangeC" style="width: 100%">
            <el-option
              v-for="dict in cOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel + '('  +dict.dictValue+ ')'"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
          </el-col>
          <el-col :span="12" :xs="24">
        <el-form-item label="危险性(D)" prop="d">
          <el-input v-model="form.d" placeholder="请输入D" disabled/>
        </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12" :xs="24">
        <el-form-item label="等级" prop="grade">
          <el-input v-model="form.grade" placeholder="请输入等级" disabled/>
        </el-form-item>
          </el-col>
          <el-col :span="12" :xs="24">
            <el-form-item label="责任主体" prop="responsibleParty">
              <el-input v-model="form.responsibleParty" placeholder="请输入责任主体" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="位置" prop="position">
          <el-input v-model="form.position" placeholder="请输入位置" type="textarea"/>
        </el-form-item>
        <el-form-item label="避免措施或控制措施" prop="measures">
          <el-input v-model="form.measures" type="textarea" placeholder="请输入避免失控措施或失控后缓解（控制）措施" />
        </el-form-item>
<!--        <el-form-item label="备注" prop="remark">-->
<!--          <el-input v-model="form.remark" placeholder="请输入备注" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="备用" prop="remarkSpare">-->
<!--          <el-input v-model="form.remarkSpare" placeholder="请输入备用" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="备用1" prop="remarkSpare1">-->
<!--          <el-input v-model="form.remarkSpare1" placeholder="请输入备用1" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="备用2" prop="remarkSpare2">-->
<!--          <el-input v-model="form.remarkSpare2" placeholder="请输入备用2" />-->
<!--        </el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
<!--        <el-button @click="showHelp">查看帮助文档</el-button>-->
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listControl, getControl, delControl, addControl, updateControl, exportControl, optionselect, overtimeControl } from "@/api/risk/control";

export default {
  name: "Control",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 风险、危险源识别评分及控制表格数据
      controlList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 危险源ID字典
      sourceIdOptions: [],
      // 输入类型种类字典
      inputTypeOptions: [],
      // 可能造成的危害种类字典
      hazardsTypeOptions: [],
      // L字典
      lOptions: [],
      // E字典
      eOptions: [],
      // C字典
      cOptions: [],
      // D字典
      dOptions: [],
      // 等级字典
      gradeOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        sourceId: null,
        revisionTime: null,
      },
      lValue: "",
      eValue: "",
      cValue: "",
      showHelpModal: false,
      helpDocumentUrl: process.env.BASE_URL + 'LEC评分规则及对应风险管控层级.pdf',
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        sourceId: [
          { required: true, message: "危险源不能为空", trigger: "blur" }
        ],
        revisionTime: [
          { required: true, message: "修订时间不能为空", trigger: "blur" }
        ],
        operatingItem: [
          { required: true, message: "作业项目不能为空", trigger: "blur" }
        ],
        riskFactor: [
          { required: true, message: "风险因素不能为空", trigger: "blur" }
        ],
        inputType: [
          { required: true, message: "输入类型种类不能为空", trigger: "blur" }
        ],
        hazardsTypes: [
          { required: true, message: "可能造成的危害种类不能为空", trigger: "blur" }
        ],
        protectiveMeasures: [
          { required: true, message: "控制措施不能为空", trigger: "blur" }
        ],
        l: [
          { required: true, message: "事故发生的可能性(L)不能为空", trigger: "blur" }
        ],
        e: [
          { required: true, message: "人员暴露于危险环境中的频繁程度(E)不能为空", trigger: "blur" }
        ],
        c: [
          { required: true, message: "一旦发生事故可能造成的后果(C)不能为空", trigger: "blur" }
        ],
        position: [
          { required: true, message: "位置不能为空", trigger: "blur" }
        ],
        responsibleParty: [
          { required: true, message: "责任主体不能为空", trigger: "blur" }
        ],
        measures: [
          { required: true, message: "避免失控措施或失控后缓解（控制）措施不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    // this.getList();
    this.getSources();
    this.getDicts("risk_input_type").then(response => {
      this.inputTypeOptions = response.data;
    });
    this.getDicts("risk_hazards_type").then(response => {
      this.hazardsTypeOptions = response.data;
    });
    this.getDicts("risk_likelihood").then(response => {
      this.lOptions = response.data;
    });
    this.getDicts("risk_exposure").then(response => {
      this.eOptions = response.data;
    });
    this.getDicts("risk_consequence").then(response => {
      this.cOptions = response.data;
    });
    this.getDicts("risk_danger").then(response => {
      this.gradeOptions = response.data;
    });
    // overtimeControl().then(response => {
    //   if (response.code === 200) {
    //
    //   } else {
    //     this.msgError(response.msg);
    //   }
    // })
  },
  watch: {
    '$route': {
      handler: function (to, from) {
        // 当路由发生变化时会调用这个方法
        // 你可以在这里处理参数变化
        if(to.params.id){
          console.log('参数变化了:', to.params.id);
          const sourceId = to.params.id;
          this.queryParams.sourceId = sourceId;
          // 你的处理逻辑
          this.getList();
        }
      },
      // 如果需要深度监听路由参数，可以设置deep: true
      deep: true
    }
  },
  mounted() {
    // 获取传递的参数
    const sourceId = this.$route.params.id;
    console.log('参数:', sourceId);
    this.queryParams.sourceId = sourceId;
    this.getList();
  },
  methods: {
    /** 查询风险、危险源识别评分及控制列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeRevisionTime && '' != this.daterangeRevisionTime) {
        this.queryParams.params["beginRevisionTime"] = this.daterangeRevisionTime[0];
        this.queryParams.params["endRevisionTime"] = this.daterangeRevisionTime[1];
      }
      listControl(this.queryParams).then(response => {
        this.controlList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
      // this.overtime();
    },
    overtime() {
      overtimeControl().then(response => {
        if (response.code === 200) {

        } else {
          this.msgError(response.msg);
        }
      })
    },
    inputTypeFormat(row, column) {
      return this.selectDictLabel(this.inputTypeOptions, row.inputType);
    },
    hazardsTypeFormat(row, column) {
      return this.selectDictLabels(this.hazardsTypeOptions, row.hazardsType);
    },
    // L字典翻译
    lFormat(row, column) {
      const dict = this.lOptions.find(dict => (dict.dictValue+"") === row.l);

      return dict ? dict.dictLabel+'\n['+dict.dictValue+'分]' : '';
      // return this.selectDictLabel(this.lOptions, row.l);
    },
    // E字典翻译
    eFormat(row, column) {
      const dict = this.lOptions.find(dict => (dict.dictValue+"") === row.e);

      return dict ? dict.dictLabel+'\n['+dict.dictValue+'分]' : '';
      // return this.selectDictLabel(this.eOptions, row.e);
    },
    // C字典翻译
    cFormat(row, column) {
      const dict = this.lOptions.find(dict => (dict.dictValue+"") === row.c);

      return dict ? dict.dictLabel+'\n['+dict.dictValue+'分]' : '';
      // return this.selectDictLabel(this.cOptions, row.c);
    },
    gradeFormat(row, column) {

      return row.d+'分['+row.grade+']';
      // return this.selectDictLabel(this.cOptions, row.c);
    },
    getSources() {
      optionselect().then(response => {
        this.sourceIdOptions = response.data;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        sourceId: null,
        revisionTime: null,
        operatingItem: null,
        riskFactor: null,
        inputType: null,
        hazardsType: null,
        protectiveMeasures: null,
        l: null,
        e: null,
        c: null,
        d: null,
        grade: null,
        position: null,
        responsibleParty: null,
        measures: null,
        remark: null,
        remarkSpare: null,
        remarkSpare1: null,
        remarkSpare2: null,
        createBy: null,
        createTime: null,
        deptId: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeRevisionTime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.getSources();
      this.reset();
      this.lValue = "";
      this.eValue = "";
      this.cValue = "";
      this.form.revisionTime = new Date();
      this.open = true;
      this.title = "添加风险、危险源识别评分及控制";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getControl(id).then(response => {
        this.form = response.data;
        this.form.revisionTime = new Date();
        this.open = true;
        this.title = "修改风险、危险源识别评分及控制";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateControl(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addControl(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除风险分级管控管理编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delControl(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有风险分级管控管理数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.exportLoading = true;
          // return exportControl(queryParams);
        this.download('/risk/control/export', {
          ...this.queryParams
        }, `风险分级管控管理.xlsx`)
        this.exportLoading = false;
        }).then(response => {
          // this.download(response.msg);
          // this.exportLoading = false;
        }).catch(() => {});
    },
    handleSelectChangeL(value) {
      this.lValue = value;
      this.eValue = this.form.e;
      this.cValue = this.form.c;
      console.log('选中的值:', value);
      this.calculationLEC();
    },
    handleSelectChangeE(value) {
      this.eValue = value;
      this.lValue = this.form.l;
      this.cValue = this.form.c;
      console.log('选中的值:', value);
      this.calculationLEC();
    },
    handleSelectChangeC(value) {
      this.cValue = value;
      this.eValue = this.form.e;
      this.lValue = this.form.l;
      console.log('选中的值:', value);
      this.calculationLEC();
    },
    calculationLEC(){
      if (this.lValue !== null && this.eValue !== null && this.cValue !== null && this.lValue !== "" && this.eValue !== "" && this.cValue !== "" ){
        let floatL = parseFloat(this.lValue);
        let floatE = parseFloat(this.eValue);
        let floatC = parseFloat(this.cValue);
        let d = floatL * floatE * floatC;
        this.form.d = d.toFixed(2);
        // 遍历字典，找到第一个满足条件的等级
        console.log(d)
        for (let i = 0; i < this.gradeOptions.length; i ++) {
          const bounds = this.gradeOptions[i].dictValue.split('-').map(Number);
          if (bounds.length>1){
            if (this.form.d >= bounds[0] && this.form.d < bounds[1]) {
              this.form.grade = this.gradeOptions[i].dictLabel;
            }
          }else {
            if (this.form.d >= bounds[0]){
              this.form.grade = this.gradeOptions[i].dictLabel;
            }
          }
        }
      }
    },
    tableRowClassName({ row, rowIndex  }) {
      console.log(row)
      if (row.grade === "Ⅰ") {
        return 'row-red';
      } else if (row.grade === "Ⅱ") {
        return 'row-orange';
      } else if (row.grade === "Ⅲ") {
        return 'row-yellow';
      } else if (row.grade === "Ⅳ") {
        return 'row-blue';
      } else if (row.grade === "Ⅴ") {
        console.log("123")
        return 'row-blue';
      }
      return '';
    },
    showHelp() {
      // this.showHelpModal = true;
      const helpDocPath = process.env.BASE_URL + 'LEC评分规则及对应风险管控层级.pdf';
      window.open(helpDocPath, '_blank');
    },
  }
};
</script>
<style>
/* 在style标签中或者单独的CSS文件中定义样式 */
.el-table .row-red {
  background: red;
}
.el-table .row-orange {
  background: #FF9E15;
}
.el-table .row-yellow {
  background: #FFFF00;
}
.el-table .row-blue {
  background: #CCFFFF;
}
.el-table .cell{
  white-space: pre-line;
}
</style>
